package ltd.followkba.page;

import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.kcbsdk.EventHandler;

import ltd.advskin.MSKIN;
import ltd.advskin.base.BasePage;

import ltd.advskin.base.KcListener;
import ltd.advskin.base.KcTypeListener;
import ltd.advskin.task.TaskFree;
import ltd.advskin.view.KcBtnProgress;
import ltd.advskin.view.KcHeaderView;
import ltd.followkba.MAPP;
import ltd.followkba.MDBS;
import ltd.followkba.R;
import ltd.followkba.task.App32;
import ltd.followkba.task.App33;
import ltd.followkba.task.App39;
import ltd.followkba.task.EditUtils;
import ltd.followkba.task.RunUtils;
import ltd.obbphoto.base.SubFunction;
import main.MAPI;

import static ltd.advskin.MSKIN.MSTRING;
import static ltd.advskin.MSKIN.MTOAST;
import static main.MAPI.mMyUtils;
import static main.MAPI.mMyWorks;

public class LoginTaskPage extends BasePage{
    private String gsResult;
    private String gsAuthSsid;
    private String gsAuthCode;

    private TextView tvAccountLogin;
    private EditText etAuthCode;
    private ImageView ivAuthCode;
    private TextView tvSsidLogin;
    private TextView tvTipsLogin;
    private KcBtnProgress kbtEnterLogin;
    private long gTick;


    // 所有的页面都接受同样的方式打开LOG
    public static boolean logEnable;
    public void MLOG(String text) {
        if (logEnable) {
            MSTRING(MAPI.GET_LOG_NAME(this) + text);
        }
    }

    @Override
    public void onInitView() {                       // 使用者需要继承，初始化页面控件等显示
        setLayout(R.layout.page_login_task);
        mKcHeaderView = findViewById(R.id.khvLogin);
        mKcHeaderView.setTitle("登录任务账号", new KcTypeListener() {
            @Override
            public void onMessage(int type) {
                switch (type) {
                    case KcHeaderView.TYPE_CLICK_LEFT:
                        onFinish();
                        break;
                }
            }
        });

        tvAccountLogin = findViewById(R.id.tvAccountLogin);
        etAuthCode = findViewById(R.id.etAuthCode);
        ivAuthCode = findViewById(R.id.ivAuthCode);
        tvSsidLogin = findViewById(R.id.tvSsidLogin);
        tvTipsLogin = findViewById(R.id.tvTipsLogin);
        kbtEnterLogin = findViewById(R.id.kbtEnterLogin);
        String appName =  MAPP.mWorksName[MAPP.mBDbsAccount.WorksType];
        String text = String.format("%s账号：%s 密码：%s", appName, MAPP.mBDbsAccount.AccountName, MAPP.mBDbsAccount.Password);
        MSKIN.setText(text, tvAccountLogin);
        text = String.format("登录%s", appName);
        MSKIN.setText(text, kbtEnterLogin);

        ivAuthCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changAuthCode();
            }
        });
        kbtEnterLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gsAuthCode = etAuthCode.getText().toString();
                MLOG(String.format("AccountNameA: %s(%s)%s", MAPP.mBDbsAccount.AccountName, MAPP.mBDbsAccount.Password, gsAuthCode));
                gsResult = null;
                loginSvr();
            }
        });
        if (MAPP.mBDbsAccount.WorksType == 33 || MAPP.mBDbsAccount.WorksType == 49) {
//            mAccount33 = new App33(MAPP.mBDbsAccount);
            tvTipsLogin.setText("提示： 如果ssid是c2开始的，可以不用输入验证码");
// javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor ..._rocrocflying的专栏-CSDN博客
// https://blog.csdn.net/rocrocflying/article/details/102798883/

        }
        MAPP.ignoreSSLHandshake();
        MLOG(String.format("makeSeretPassword: %s %s", mMyUtils.makeSeretPassword("cc12345678"), mMyUtils.makeSeretPassword("d27951479")));
    }
    @Override
    public void onInitData(){                                                                       // onInitView结束，开始加载数据
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (MAPP.mBDbsAccount.WorksType == 33 || MAPP.mBDbsAccount.WorksType == 49) {
                    App33.setUser(null);                                                            // App33需要一个默认的账号
                }
                if (true) {
//                App39 app39 = new App39(null);
                    App39.getPoemInfo("6184");

                }
            }
        }).start();

//
//                app39.getCareList("20234508", 0);
//
////            app39.getUserInfo("20234508");
////            app39.searchUser("快乐解忧");
////
//                String[] userIdS = app39.searchUser("刘工21");        // 快乐解忧
//                if (userIdS != null) {
//                    MLOG("bAppUser.WorksS[index].userIdS[0] " + userIdS[0]);
//                    BAppUser bAppUser = app39.getUserInfo(userIdS[0], false);
//                    if (bAppUser != null && bAppUser.WorksS != null) {
////                    BAppWorks bAppWorks = app39.getWorksInfo(bAppUser.UserIdS, bAppUser.WorksS[0].IdS);
//                        MLOG("bAppUser.WorksS[index].IdS[0] " + bAppUser.WorksS.length);
////                    MLOG("bAppUser.WorksS[index].IdS[0] "+bAppWorks);
//                    }
//
//                }
//            }
//            0x0203 S 蝶恋妃 null http://poem.weinisongdu.com/upload/lyric/default/b0000104.lrc

        mMyWorks.setUiEventCallBack(new EventHandler() {
            @Override
            public void onComplete(int methodType, boolean isFail, String message) {
                if (methodType > 0) {
                }else {
                    if (mMyWorks.isEventDataRefresh()){
                        showInfo();
                    }
                }
            }
        });
        changAuthCode();
        showInfo();
    }
    @Override
    public void onPageUpdate(BasePage basePage) {    // 更新显示页面数据，用于刷新显示 basePage返回上面的页面，可以使用getPageResult()获得返回的内容
        onInitData();
    }
    @Override
    public void onFinish() {       // 使用者选择性继承，用户按了后退键，不继承就直接关闭了
        setClose();
    }
    private void showInfo() {

        MSKIN.setBitmap(gsResult, ivAuthCode);
        tvSsidLogin.setText("ssid：" + gsAuthSsid);
        MAPP.mBDbsAccount.UserName = mMyUtils.getNickName(MAPP.mBDbsAccount);
    }
    private void loginSvr() {
        kbtEnterLogin.setProgress(2);
        gsResult = null;
        new TaskFree(null, new TaskFree.Listener() {
            @Override
            public void onMessage(boolean isThread, Object object) {
                MLOG(String.format("AccountNameAb: %s(isThread:%s)", MAPP.mBDbsAccount.AccountName, isThread));
                if (isThread){
                    MAPP.MTOAST("正在登录...");
                    if (MAPP.mBDbsAccount.WorksType < 32) {
                        if (MAPI.isEmpty(gsAuthCode)) {
gsAuthCode = "8888";
                        }
//                        if (app32 != null) {
                            MLOG(String.format("AccountNameAc: %s(%s)%s", MAPP.mBDbsAccount.AccountName, MAPP.mBDbsAccount.Password, gsAuthCode));
                            gsResult = App32.loginSvr(MAPP.mBDbsAccount.AccountName, MAPP.mBDbsAccount.Password, gsAuthCode, MAPP.mBDbsAccount);
                            MLOG(String.format("AccountNameAe: %s(%s)", MAPP.mBDbsAccount.AccountName, gsResult));

//                        }
                        if ("ok".equals(gsResult)) {
                            MLOG(String.format("changeUserA %s %s %s", MAPP.mBDbsAccount.LoginFlag, mMyUtils.getCurrentLoginUserID(), mMyUtils.getCurrentUserID()));
                            MAPP.MTOAST("成功登录...");
                        }else {
                            gsResult = MAPP.mBDbsAccount.Status;
                            MAPP.MTOAST("登录出错 "+gsResult);
                        }
                    }else if (MAPP.mBDbsAccount.WorksType == 33 || MAPP.mBDbsAccount.WorksType == 49) {
                        MLOG(String.format("app33 A %s(%s)", App33.gsUserID, App33.LoginFlag));
                        gsResult = App33.loginSvr(MAPP.mBDbsAccount.AccountName, MAPP.mBDbsAccount.Password, gsAuthCode, MAPP.mBDbsAccount);
                        MLOG(String.format("app33 A1 %s(%s)%s", gsResult, App33.gsUserID, App33.LoginFlag));

                        MLOG(String.format("AccountNameAc: %s(%s)", MAPP.mBDbsAccount.AccountName, MAPP.mBDbsAccount.Status));
                        if ("ok".equals(gsResult)){
//                            App33 = new App33(MAPP.mBDbsAccount);
                            gsResult = App33.checkLogin();
//                            gsResult = app33.addCareUser("135756689");
                            MLOG(String.format("app33 B %s(%s)", App33.gsUserID, App33.LoginFlag));
                            MLOG(String.format("AccountNameAd: %s(%s)", MAPP.mBDbsAccount.AccountName, gsResult));
                        }else {
                            gsResult = MAPP.mBDbsAccount.Status;
                        }
                        if (gsResult != null){
                            if (gsResult.indexOf("封禁") >= 0) {
                                MAPP.mBDbsAccount.Status = "已封禁";
                                RunUtils.saveBDbsAccount(MAPP.mBDbsAccount);
                            } else if (gsResult.indexOf("异常") >= 0) {
                                MAPP.mBDbsAccount.Status = "账号异常";
                                RunUtils.saveBDbsAccount(MAPP.mBDbsAccount);
                            }
                        }
                    }
                    if ("ok".equals(gsResult)) {
//                        gsResult = "ok";
                        EditUtils editUtils = new EditUtils();
                        MLOG(String.format("AccountNameAB: %s(%s)", MAPP.mBDbsAccount.AccountName, gsResult));
                        editUtils.getAndSaveBDbsAccountInfo(new KcListener() {
                            @Override
                            public void onMessage(Object o) {
                                MTOAST("登录成功");
//                                setPageResult(MAPP.mBDbsAccount);                        // 需要重新makeBDbsAccount
                                setClose();
                            }
                        });
                    }
                    return;
                }
                if ("ok".equals(gsResult)) {
                    kbtEnterLogin.setText("正在保存");
                }else {
                    String text = String.format("登录出错：%s", gsResult);
                    tvTipsLogin.setText(text);
                    MTOAST(text, 5000);
                }
                kbtEnterLogin.setProgress(2 + 100);

            }
        });
    }


    private void changAuthCode(){
        if (gTick != 0) {
            MTOAST(String.format("换一张 %sms", System.currentTimeMillis() - gTick), 2000);
        }else {
            MTOAST("换一张", 2000);
        }
        new TaskFree(null, new TaskFree.Listener() {
            @Override
            public void onMessage(boolean isThread, Object object) {
                if (isThread){
                    gTick = System.currentTimeMillis();
                    if (MAPP.mBDbsAccount.WorksType < 32) {
                        gsResult = App32.getAuthCode();
                    }else if (MAPP.mBDbsAccount.WorksType == 33 || MAPP.mBDbsAccount.WorksType == 49) {
                        gsResult = App33.getAuthCode();
                        gsAuthSsid = App33.gsAuthSsid;
                    }
                    if (MAPI.GET_FILE_LENGTH(gsResult) < 500){
                        MTOAST("图形验证码下载出错", 2000);
                    }
                    MLOG(String.format("changAuthCode %s %s", MAPI.GET_FILE_LENGTH(gsResult), gsResult));
                    return;
                }
                showInfo();
                gTick = 0;
            }
        });
    }


}


